<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="plus" @click="handleAdd">添加品牌</el-button>
    <el-table style="margin: 10px 0px" border :data="tradeAttrList">
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称">
        <template #="{ row, column, $index }">
          <span>{{ row.tmName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, column, $index }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, column, $index }">
          <el-button type="primary" size="small" icon="Edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="Delete"
            width="250px"
            icon-color="#ff0000"
            :title="`您确定要删除【${row.tmName}】吗？`"
            @confirm="confirmEvent(row.id)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="true"
      :pager-count="7"
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 10, 20]"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
  </el-card>

  <el-dialog :title="trademarkParam.id ? '编辑品牌' : '添加品牌'" v-model="dialogFormVisible">
    <el-form style="width: 80%" :model="trademarkParam" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="trademarkParam.tmName" placeholder="请输入品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!--upload组件属性：
          action图片上传路径书写要带上/api，否则代理服务器不发送post请求
          show-file-list:是否显示已上传文件列表
          on-success:上传成功回调函数
          before-upload:上传前回调函数
        -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParam.logoUrl" :src="trademarkParam.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!--具名插槽footer，用于自定义弹窗底部按钮-->
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElPopconfirm, type UploadProps } from 'element-plus'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  ITrademarkResponseData,
  ITrademark,
  IResponseData,
} from '@/api/product/trademark/type'

//获取el-form组件实例
let formRef = ref<any>()

//定义收集新增品牌数据
let trademarkParam = reactive<ITrademark>({
  tmName: '',
  logoUrl: '',
})
//当前页码
let pageNo = ref<number>(1)
//每一页展示多少条数
let limit = ref<number>(3)
//已有品牌数据总数
let total = ref<number>(0)
//存储数组
let tradeAttrList = ref<Records>([])

//弹窗是否显示
let dialogFormVisible = ref<boolean>(false)

//将获取已有品牌的接口封装为一个函数：在任何情况下向获取数据，调用此函数即可
const getHasTrademark = async (pager = 1) => {
  let result: ITrademarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
  if (result.code == 200) {
    total.value = result.data.total
    tradeAttrList.value = result.data.records
  }
  console.log(result)
}

onMounted(() => {
  getHasTrademark()
})

//分页事件,当前页码发生改变时触发
const handleCurrentChange = () => {
  //会返回重新设置的当前页码，并且自动收集当前页码到pageNo
  getHasTrademark()
}

//每页显示条数改变时触发
const handleSizeChange = () => {
  //会返回重新设置的每页显示条数，并且自动收集当前页码到limit
  //当每页显示条数改变时，需要将当前页码重置为1
  pageNo.value = 1
  getHasTrademark()
}

const handleAdd = () => {
  //打开弹窗
  dialogFormVisible.value = true
  //清空表单数据,这样表单弹框中确定和取消不用都清空
  trademarkParam.id = 0
  trademarkParam.tmName = ''
  trademarkParam.logoUrl = ''
  //清理表单校验规则
  //第一种写法：?. 运算符 ,由于第一次el-form还没有渲染，所以加上空值判断
  //formRef.value?.clearValidate('tmName')
  //formRef.value?.clearValidate('logoUrl')
  //第二种写法：nextTick
  nextTick(() => {
    //console.log(formRef.value)
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

const handleEdit = (row: ITrademark) => {
  //打开弹窗
  dialogFormVisible.value = true
  //将要编辑的数据赋值给表单
  // trademarkParam.id = row.id
  // trademarkParam.tmName = row.tmName
  // trademarkParam.logoUrl = row.logoUrl
  //以上多个赋值可以通过以下一行代码完成赋值
  Object.assign(trademarkParam, row)
  //注意点：编辑状态下清理表单错误校验规则
  nextTick(() => {
    //console.log(formRef.value)
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

const handleSubmit = async () => {
  //在发送请求之前，对整个表单的校验,获取校验规则,只有校验通过才会继续往下执行
  await formRef.value.validate()
  //提交数据
  let result: any = await reqAddOrUpdateTrademark(trademarkParam)
  if (result.code == 200) {
    //关闭弹窗
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParam.id ? '修改品牌成功！' : '添加品牌成功!',
    })
    //再次获取数据，刷新页面
    getHasTrademark(trademarkParam.id ? pageNo.value : 1)
  } else {
    //关闭弹窗
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: trademarkParam.id ? '修改品牌失败！' : '添加品牌失败!',
    })
  }
}

//上传图片组件，上传图片之前触发的钩子函数，用于校验文件格式和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // rawFile: 文件对象，包含以下属性：
  // uid: 文件唯一标识
  // name: 文件名
  // size: 文件大小
  // type: 文件类型
  // lastModified: 文件最后修改时间
  // lastModifiedDate: 文件最后修改时间
  // webkitRelativePath: 文件路径

  // 校验文件格式和大小
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件类型必须是jpg/png/gif!',
    })
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage({
      type: 'error',
      message: '上传的文件大小不能超过2M!',
    })
    return false
  }
  return true
}

//图片上传成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //response:本次上传图片post请求服务器返回的数据
  //uploadFile: 上传文件对象，包含以下属性：
  //uid: 文件唯一标识
  //raw: 文件对象
  //response: post请求服务器返回的数据
  //status: 状态码
  //name: 文件名
  //size: 文件大小
  //percentage : 上传进度
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log(response)
  trademarkParam.logoUrl = response.data
  //细节要点：如果图片上传成功，清除图片校验规则
  formRef.value.clearValidate('logoUrl')
}

//气泡确认框按钮的回调
const confirmEvent = async (id: number) => {
  let response: IResponseData = await reqDeleteTrademark(id)
  if (response.code == 200) {
    ElMessage({
      type: 'success',
      message: '品牌删除成功!',
    })
    //再次获取数据，刷新页面
    getHasTrademark(tradeAttrList.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '品牌删除失败!',
    })
  }
}

//气泡取消框按钮的回调
const cancelEvent = () => {
  console.log('cancel!')
}

//表单校验规则
const rules = {
  tmName: [
    {
      //该字段要校验
      required: true,
      //校验时机,失去焦点触发
      trigger: 'blur',
      //校验规则
      validator: (rule: any, value: any, callback: any) => {
        //自定义校验规则
        if (value.trim().length >= 2) {
          callback()
        } else {
          //校验未通过时，返回错误信息
          callback(new Error('品牌名称长度必须大于等于2'))
        }
      },
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        //value是图片的地址
        if (value) {
          callback()
        } else {
          //校验未通过时，返回错误信息
          callback(new Error('LOGO图片必须上传！'))
        }
      },
    },
  ],
}
</script>

<style scoped>
.box-card {
  width: calc(100% - 40px);
  margin: 10 auto;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
